package com.morgan.basemodule.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import java.io.File

/**
 * description：android 7以上 需要file转成uri的适配
 * <br></br>author：caowugao
 * <br></br>time：2021/4/21 0021 16:10
 */
class FileProviderCompat private constructor(){
//https://blog.csdn.net/lmj623565791/article/details/72859156
    companion object {
        /**
         * 如
         *
         * 新建res/xml/file_paths.xml文件
         *
         * <provider android:name="androidx.core.content.FileProvider"
         *      android:authorities="${applicationId}.android7.fileprovider"
         *      android:exported="false" android:grantUriPermissions="true">
         *      <meta-data
         *          android:name="android.support.FILE_PROVIDER_PATHS"
         *          android:resource="@xml/file_paths">
         *      </meta-data>
            </provider>
         *
         * @param context
         * @param file
         * @param endAuthorities 为 .android7.fileprovider
         * @return
         */
        fun getUriForFile(context: Context, file: File, endAuthorities: String): Uri? {
            var fileUri: Uri? = null
            fileUri = if (Build.VERSION.SDK_INT >= 24) {
                getUriForFile24(context, file, endAuthorities)
            } else {
                Uri.fromFile(file)
            }
            return fileUri
        }

        /**
         *
         * @param context
         * @param file
         * @param endAuthorities
         * @return
         */
        fun getUriForFile24(context: Context, file: File, endAuthorities: String): Uri =
            FileProvider.getUriForFile(context, context.packageName + endAuthorities, file)


        fun setIntentDataAndType(
            context: Context,
            intent: Intent,
            type: String?,
            file: File,
            endAuthorities: String,
            writeAble: Boolean
        ) {
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setDataAndType(getUriForFile(context, file, endAuthorities), type)
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                if (writeAble) {
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                }
            } else {
                intent.setDataAndType(Uri.fromFile(file), type)
            }
        }
    }
}